<template>
  <div class="app-container" :loading="submitLoading">
    <div class="filter-container">
      <div style="align-items: center;display: flex;">
        <div>
          <el-input v-model="listQuery.title" placeholder="搜索关键字" clearable></el-input>
        </div>
        <el-button type="primary" icon="el-icon-search" @click="searchList()">
          搜索
        </el-button>
        <el-button type="primary" icon="el-icon-refresh-right" @click="Refresh()">
          刷新
        </el-button>
        <el-button type="primary" icon="el-icon-edit" @click="handleCreate">
          添加
        </el-button>
      </div>
    </div>
    <!-- 列表 -->
    <el-table :data="list" border style="width: 100%;" v-loading="submitLoading">
      <el-table-column label="id" prop="id" align="center" width="90">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" width="260">
        <template slot-scope="scope">
          <span class="link-type" @click="list_detail(scope)">{{scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center">
        <template scope="scope">
          <div>
            <div class="demo-image__preview">
              <el-image style=" height: 50px" :src="scope.row.img_src" fit="scale-down" :preview-src-list="list_for">
              </el-image>
            </div>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="链接:">
        <template slot-scope="{row}">
          <span>{{ row.img_src }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="排序" prop="sort" width="120" align="center">
      </el-table-column>
      <!-- <el-table-column label="日期" align="center">
        <template slot-scope="{row}">
          <span>{{ row.add_time}}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="修改" placement="top">
            <el-button size="mini" icon="el-icon-edit" type="success" @click="edit(scope)">
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-popconfirm title="确定删除吗？" @onConfirm="submit_delete(scope)">
              <el-button slot="reference" style="margin-left: 10px;" size="mini" icon="el-icon-delete" type="danger">
                <!-- 删除 -->
              </el-button>
            </el-popconfirm>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 弹框 -->
    <el-dialog title="添加" :visible.sync="popup_add_show" width="50%" center>
      <div class="conal">
        <el-form label-width="100px" style="text-align: left;" :model="ruleForm" status-icon :rules="rules"
          ref="ruleForm" class="demo-ruleForm">
          <el-form-item label="标题:" prop="title">
            <el-input v-model="ruleForm.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item label="图片链接:" prop="banner_url">
            <el-input v-model="ruleForm.banner_url" placeholder="可以直接输入图片的网络地址"></el-input>
          </el-form-item>
          <el-form-item label="上传图片:">
            <div>
              <el-upload class="avatar-uploader" :headers="token_upload"
                action="/market/content/upload" :show-file-list="false"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </el-form-item>
          <el-form-item label="排序" style="width: 60%;">
            <el-input v-model="ruleForm.sort" type="number" placeholder="请输入排序"></el-input>
            <span class="sort-class">排序从大到小</span>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="popup_add_show = false">取 消</el-button>
        <el-button type="primary" :loading="circle" @click="submit_add()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 详情-->
    <el-dialog title="详情" :visible.sync="popup_details_show" width="50%" center>
      <div class="conal">
        <el-form ref="banner_details" :model="banner_details" label-width="100px" style="text-align: left;">
          <el-form-item label="标题:">
            <div>{{banner_details.title}}</div>
          </el-form-item>
          <el-form-item label="banner:">
            <div>
              <img :src="banner_details.img_src" style="width: 100%;height: 100%;background-size: 100% 100%;">
            </div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="popup_details_show = false">取 消</el-button>
        <el-button type="primary" @click="popup_details_show = false">
          确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog title="编辑" :visible.sync="popup_edit_show" width="50%" center>
      <div>
        <el-form label-width="100px" style="text-align: left;" :model="edit_list" status-icon :rules="rules"
          ref="edit_list" class="demo-ruleForm conal">
          <el-form-item label="标题:" prop="title">
            <el-input v-model="edit_list.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item label="上传图片:">
            <el-upload class="avatar-uploader" :headers="token_upload" action="/market/content/upload"
              :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="edit_list.xiu_img" :src="edit_list.xiu_img" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="排序:" style="width: 60%;">
            <el-input v-model="edit_list.sort" type="number" placeholder="请输入排序"></el-input>
            <span class="sort-class">排序从大到小</span>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="popup_edit_show = false">取 消</el-button>
        <el-button type="primary" :loading="circle" @click="submit_edit()">
          确 定</el-button>
      </span>
    </el-dialog>
    <div class="fenye">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="page_limit"
        layout="total, sizes, prev, pager, next, jumper" :total="page_count">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  import {
    banner_list,
    banner_del,
    banner_detail,
    banner_edit,
    banner_add
  } from '@/api/setup/setup_banner.js'
  export default {
    name: 'ComplexTable',
    data() {
      return {
        listLoading: false,
        submitLoading: false,
        ruleForm: {
          title: "",
          banner_url: "",
          sort: 0,
        },
        rules: {
          title: [{
            required: true,
            message: '请输入标题',
            trigger: 'blur'
          }],
          banner_url: [{
            required: true,
            message: '图片链接',
            trigger: 'blur'
          }],
        },
        circle: false,
        //修改列表
        edit_list: {
          xiu_img: ''
        },
        //各个弹框
        popup_edit_show: false,
        popup_add_show: false,
        popup_details_show: false,
        //详情
        banner_details: {},
        //图片放置
        imageUrl: '',
        //banner列表
        list: [],
        //搜索
        listQuery: {
          title: "",
        },
        //列表放大图片
        list_for: [],
        // tableKey: 1,
        currentPage: 1,
        page_count: 0,
        page_limit: 10,
        token_upload: {}
      }
    },
    created() {},
    mounted() {
      this.reqery()
      console.log(this.$store.state.user.token)
      this.token_upload = {
        "token": this.$store.state.user.token
      }
    },
    methods: {
      handleAvatarSuccess(res, file) {
        let _this = this
        new Promise(function(resolve, reject) {
            console.log(file,"bbb")
            //upload内部需要一个promise,简单的return出false并没有什么用
            let width = 1647;
            let height = 268;
            let _URL = window.URL || window.webkitURL;
            let img = new Image();
            img.onload = function() {
              let valid = img.width == width && img.height == height;
              valid ? resolve() : reject();
            };
            img.src = _URL.createObjectURL(file.raw); //onload是异步加载
          }).then(
          () => {
            let isJPG = file.raw.type === 'image/jpeg';
            let isPNG = file.raw.type === 'image/png';
            let isLt2M = file.raw.size / 1024 / 1024 < 2;
            console.log(isJPG,"222222")
            if (!isJPG && !isPNG) {
              this.$message.error('上传头像图片只能是 JPG 格式 或者 PNG 格式!');
            }else if(!isLt2M){
              this.$message.error('上传头像图片大小不能超过 2MB!');
            }else{
              _this.imageUrl = URL.createObjectURL(file.raw);
              this.imageUrl = URL.createObjectURL(file.raw);
              this.ruleForm.banner_url = res.data.src
              console.log(res.data.src, "www")
              this.edit_list.xiu_img = res.data.src
            }
            // if (!isLt2M) {
            //   this.$message.error('上传头像图片大小不能超过 2MB!');
            // }else{
            //   _this.imageUrl = URL.createObjectURL(file.raw);
            // }
            // return isJPG && isLt2M;
            // return (isJPG || isPNG) && isLt2M;
            // return file.raw;

            // this.imageUrl = URL.createObjectURL(file.raw);
            // this.ruleForm.banner_url = res.data.src
            // console.log(res.data.src, "www")
            // this.edit_list.xiu_img = res.data.src
          },
          () => {
            console.log("3333")
            this.$message.error("上传的图片必须是 1647*268!");
            return Promise.reject();
            return false;
          }
        );

      },
      beforeAvatarUpload(file) {
        console.log(file,"ccccc")
        // const isJPG = file.type === 'image/jpeg';
        // const isPNG = file.type === 'image/png';
        // const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isJPG && !isPNG) {
        //   this.$message.error('上传头像图片只能是 JPG 格式 或者 PNG 格式!');
        // }
        // if (!isLt2M) {
        //   this.$message.error('上传头像图片大小不能超过 2MB!');
        // }
        // return (isJPG || isPNG) && isLt2M;
      },
      reqery() {
        this.submitLoading = true
        console.log(122133333333)
        banner_list().then(res => {
          this.list = res.data
          this.page_count = res.count
          console.log(this.list)
          let a = []
          this.list.forEach(function(res) {
            console.log(res.img_src.toString())
            a.push(res.img_src.toString())
          })
          console.log(a)
          this.list_for = a
          this.submitLoading = false
        })
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.submitLoading = true
        this.page_limit = val
        banner_list(1, this.page_limit).then(res => {
          if (res.code == 200) {
            this.list = res.data
            this.page_count = res.count
            console.log(this.page_count)
            this.submitLoading = false
          }
        })
      },
      handleCurrentChange(val) {
        this.submitLoading = true
        console.log(`当前页: ${val}`);
        this.currentPage = val
        banner_list(this.currentPage, this.page_limit).then(res => {
          console.log(res)
          this.list = res.data
          this.page_count = res.count
          this.submitLoading = false
        })
      },
      handleCreate(val) {
        let that = this
        that.popup_add_show = true
      },
      submit_add() {
        console.log(this.ruleForm.title, this.ruleForm.banner_url, this.ruleForm.sort)
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            banner_add(this.ruleForm.title, this.ruleForm.banner_url, this.ruleForm.sort).then(res => {
              console.log(res)
              this.circle = true
              if (res.code == 200) {
                this.circle = false
                this.$message({
                  message: res.msg,
                  type: 'success'
                });
                this.popup_add_show = false
                this.ruleForm.title = ""
                this.ruleForm.banner_url = ""
                this.ruleForm.sort = 0
                this.reqery()
              }
            })
          }
        })
      },
      submit_delete(val) {
        let that = this
        banner_del(val.row.id).then(res => {
          console.log(res)
          if (res.code == 200) {
            this.$message({
              message: res.msg,
              type: 'success'
            });
            this.reqery()
          }
        })
      },
      list_detail(val) {
        console.log(val)
        let that = this
        that.popup_details_show = true
        banner_detail(val.row.id).then(res => {
          console.log(res)
          that.banner_details = res.data
        })
      },
      searchList() {
        let that = this
        console.log(this.listQuery.title, "时间离开")
        this.submitLoading = true
        banner_list(1, this.page_limit, this.listQuery.title).then(res => {
          console.log(res)
          if (res.code == 200) {
            this.$message({
              message: res.msg,
              type: 'success'
            });
            this.list = res.data
            this.page_count = res.count
            this.submitLoading = false
          }
        })
      },
      edit(scope) {
        let that = this
        that.popup_edit_show = true
        that.edit_list = scope.row
        that.edit_list.xiu_img = scope.row.img_src
        console.log(that.edit_list, "显示")
      },
      submit_edit() {
        let that = this
        this.$refs.edit_list.validate((valid) => {
          if (valid) {
            that.circle = true
            banner_edit(that.edit_list.id, that.edit_list.title, that.edit_list.xiu_img,
              that.edit_list.sort).then(res => {
              console.log(res)
              if (res.code == 200) {
                this.circle = false
                this.$message({
                  message: res.msg,
                  type: 'success'
                });
                that.popup_edit_show = false
                that.reqery()
              }
            })
          }
        })
      },
      Refresh() {
        this.submitLoading = true
        this.listQuery.title = ""
        this.listQuery.searchTime = ""
        banner_list(1, 10, "").then(res => {
          console.log(res)
          if (res.code == 200) {
            this.list = res.data
            this.submitLoading = false
            this.page_count = res.count
            this.currentPage = 1
            this.page_limit = 10
          }
        })
      },
    }
  }
</script>
<style type="text/css">
  .sort-class {
    color: #67B5F4;
    font-size: 12px;
  }

  .sortable-ghost {
    opacity: .8;
    color: #fff !important;
    background: #42b983 !important;
  }

  .fenye {
    padding: 20px 0px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100%;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 100%;
    height: 100%;
    display: block;
  }

  .avatar-uploader .el-upload {
    width: 100%;
  }

  .conal {
    padding-right: 20px;
    overflow: auto;
    height: 500px;
  }
</style>
